package com.sx.micowell.module.train

import android.view.Gravity
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.until.Tips
import com.example.mvvm.until.ToastUtils
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.google.gson.Gson
import com.miloyu.modelnet.response.TrainSelectData
import com.miloyu.modelnet.response.log
import com.miloyu.modelnet.response.replaceFragment
import com.sx.micowell.BR
import com.sx.micowell.R
import com.sx.micowell.databinding.FragTrainChildBinding
import com.sx.micowell.framework.adapter.TrainStepAdapter
import com.sx.micowell.framework.app.IntentKey
import com.sx.micowell.framework.app.MyFragment
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.model.TrainModel
import com.sx.micowell.framework.tools.AppDialogUtils
import com.sx.micowell.framework.view.chartManager.AngleByIndex
import com.sx.micowell.framework.view.chartManager.UI
import com.sx.micowell.framework.view.chartManager.setMoreDataColors
import com.sx.micowell.framework.view.chartManager.setPieData
import com.sx.micowell.module.MainActivity
import com.sx.micowell.module.train.run.scene.TrainRunSceneFragment
import com.sx.micowell.module.train.run.time.TrainRunTimeFragment
import com.sx.micowell.module.train.setting.TrainStepSettingFragment
import com.sx.widget.app.DisplayUtil
import kotlinx.android.synthetic.main.frag_train_child.*
import com.tuya.smart.home.sdk.TuyaHomeSdk
import kotlin.streams.toList

/**
 * @Description 训练步骤
 * @Author 梁浩文
 * @Date 2021/8/27 14:13
 */
@Route(path = RoutePath.Train_STEP)
class TrainStepFragment : MyFragment<FragTrainChildBinding, MainActivity>() {

    @Autowired(name = IntentKey.TYPE)
    @JvmField
    var type: Int = 0
    var trainStepSettingFragment: TrainStepSettingFragment? = null
    var trainRunSceneFragment: TrainRunSceneFragment? = null
    var trainRunTimeFragment: TrainRunTimeFragment? = null

    private val viewModel: TrainModel by lazy {
        getFragmentScopeViewModel(TrainModel::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig =
        DataBindingConfig(R.layout.frag_train_child, BR.viewModel, viewModel)
            .addBindingParam(BR.adapter, context?.let {
                TrainStepAdapter(
                    viewModel.trainStepSelectList,
                    it
                )
            })

    override fun initView() {

        binding.stepLast.setOnClickListener(this)
        binding.stepSure.setOnClickListener(this)
        binding.sportStart.setOnClickListener(this)
        var windowsWidth = DisplayUtil.getWindowsWidth(context) / 2
        inside_chart.setMoveToListener {
            //(inside_chart.width+inside_chart.left)/2f
            var highlightByTouchPoint = it.getHighlightByTouchPoint(
                windowsWidth.toFloat() - inside_chart.left,
                0f
            )

            setDataInColors(highlightByTouchPoint)
        }
        inside_chart.setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
            override fun onValueSelected(e: Entry?, h: Highlight?) {
                var entry = e as PieEntry
                var id = entry.label.split("_")[1].toInt()
                if (id == 1028) {
                    viewModel.trainStepSelectList.value?.let {
                        if (!it.contains(TrainSelectData(1018, null))) {
                            Tips.show(
                                context, "请先选择锻炼部位再设置动作设定", Toast.LENGTH_SHORT,
                                Gravity.CENTER or Gravity.BOTTOM
                            )
                            return
                        }
                    }
                }
                inside_chart.AngleByIndex(h!!.x.toInt())
                setDataInColors(h)
                returnSecondData(entry.label.split("_")[1].toInt())
            }

            override fun onNothingSelected() {

            }
        })
        outside_chart.setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
            override fun onValueSelected(e: Entry?, h: Highlight) {
                //1015是单选
                var pieEntry = e as PieEntry
                var toInt = pieEntry.label.split("&")[1].toInt()
                if (toInt == 1015 || toInt == 1031) {
                    //单选
                    viewModel.currentSelectSecondType.clear()
                }
                if (viewModel.currentSelectSecondType.contains(h.x.toInt())) {
                    viewModel.currentSelectSecondType.remove(h.x.toInt())
                } else {
                    viewModel.currentSelectSecondType.add(h.x.toInt())
                }
                outside_chart.setMoreDataColors(viewModel.currentSelectSecondType)
            }

            override fun onNothingSelected() {

            }
        })
    }

    //自己慢慢看
    fun returnSecondData(oneId: Int) {
        viewModel.currentSelectSecondType.clear()
        var data = viewModel.trainStepSelectList.getData(TrainSelectData(oneId, null))
        data?.let {
            if (it.child is String) {
                var ids = it.child as String
                if(oneId==1015){
                    ids=ids.split("&")[1]
                }
                var idList = ids.split(",")
                outside_chart.data?.let {
                    var dataSet = it.dataSet as PieDataSet
                    var entries = dataSet.entries as List<PieEntry>
                    for (entry in entries) {
                        var childId = entry.label.split("_")[1].split("&")[0]
                        if (idList.contains(childId)) {
                            viewModel.currentSelectSecondType.add(entries.indexOf(entry))
                        }
                    }
                    outside_chart.setMoreDataColors(viewModel.currentSelectSecondType)
                }
            }

        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel.loadSuccessEvent.observe(this) {
            viewModel.trainOnList.value?.let { it1 -> inside_chart.setPieData(it1) }
        }
        viewModel.pieShow.observe(this) {
            if (viewModel.trainStepList.size != 0 && viewModel.trainStepList.size == getCurrentStep()) {
                binding.stepSure.visibility = View.GONE
                binding.sportStart.visibility = View.VISIBLE
            } else {
                binding.stepSure.visibility = View.VISIBLE
                binding.sportStart.visibility = View.GONE
            }
        }
    }

    override fun initData() {
        viewModel.type = type
        viewModel.reqTrainList()
        inside_chart.UI()
        inside_chart.setRotationEnabled(false)
        outside_chart.UI()
        inside_chart.holeRadius = resources.getDimension(R.dimen.dp_15)
        outside_chart.holeRadius = resources.getDimension(R.dimen.dp_20)

    }

    var lastHigh_in: Highlight? = null;

    fun setDataInColors(currentHigh: Highlight?) {
        if (currentHigh != null && !currentHigh.equalTo(lastHigh_in)) {
            var pieEntry =
                inside_chart.data.dataSet.getEntryForIndex(currentHigh!!.x.toInt()) as PieEntry
            viewModel.tabText.set(pieEntry.label.split("_")[0])
            lastHigh_in = currentHigh
            //02D98E
            viewModel.currentSelectId = pieEntry.label.split("_")[1].toInt()
            viewModel.currentSelectOneType.clear()
            viewModel.currentSelectOneType.add(currentHigh.x.toInt())
            var toList =
                viewModel.trainStepSelectList.value!!.stream().map { it.oneX }.toList() as List<Int>
            inside_chart.setMoreDataColors(viewModel.currentSelectOneType, toList)
            var list =
                viewModel.trainSecondList[pieEntry.label.split("_")[1].toInt()] as? List<PieEntry>
            viewModel.currentSelectSecondType.clear()
            if (list != null && list.size > 0) {
                outside_chart.visibility = View.VISIBLE
                list?.let { outside_chart.setPieData(it) }
            } else {
                outside_chart.visibility = View.INVISIBLE
            }

        }
    }


    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.step_last -> {
                //取消
                viewModel.pieShow.value = true
                binding.sportStart.visibility = View.GONE
                binding.stepSure.visibility = View.VISIBLE
                binding.trainLayout.visibility = View.GONE
                binding.trainTurn.visibility = View.VISIBLE
            }
            R.id.sport_start -> {
                //开始运动
                var toJson = Gson().toJson(viewModel.trainStepSelectList.value)
                viewModel.context.startContainerFragment(
                    RouteManager.getInstance().getFragPlayCountDownFragment(type, toJson)
                )
                viewModel.trainStepSelectList.clean()
                viewModel.currentSelectId = null
                viewModel.currentSelectOneType.clear()
                viewModel.currentSelectSecondType.clear()
                viewModel.trainStepList.callValue()
                viewModel.pieShow.value = true
                binding.trainLayout.visibility = View.GONE
                binding.trainTurn.visibility = View.VISIBLE
                binding.sportStart.visibility = View.GONE
                binding.stepSure.visibility = View.VISIBLE
                inside_chart.AngleByIndex(0)
                inside_chart.invalidate()
            }
            R.id.step_sure -> {
                //确定
                if(type==2&&!TuyaHomeSdk.getUserInstance().isLogin){
                    AppDialogUtils.showBasicDialog(
                        context, "提示", "请登录智能设备",
                        object : AppDialogUtils.IOnClickListener {
                            override fun leftListener() {}
                            override fun rightListener() {
                                RouteManager.getInstance().intentDeviceLogin()
                            }
                        })
                    return
                }
                if (viewModel.currentSelectOneType.size > 0) {
                    if (outside_chart.visibility == View.INVISIBLE) {
                        viewModel.currentSelectId?.let {
                            clickJump(it)
                        }
                    } else {
                        if (viewModel.currentSelectSecondType.size > 0) {
                            //根据二级分类的索引获取id
                            viewModel.currentSelectSecondType.stream()
                                .map {
                                    if (viewModel.currentSelectId == 1015) {
                                        var label =
                                            viewModel.trainSecondList[viewModel.currentSelectId]!!.get(
                                                it
                                            ).label
                                        label.log()
                                        label.split("&")[2] + "&" + label.split("&")[0].split("_")[1]
                                    } else {
                                        viewModel.trainSecondList[viewModel.currentSelectId]!!.get(
                                            it
                                        ).label.split(
                                            "_"
                                        )[1].split("&")[0]
                                    }

                                }
                                .toList().joinToString(separator = ",")
                                .let { clickStep(viewModel.currentSelectId!!, it) }
                        } else {
                            ToastUtils.showShort("请选择第二步")
                        }
                    }
                } else {
                    ToastUtils.showShort("请选中第一步")
                }
            }
        }

    }

    fun clickJump(oneId: Int) {
        if (viewModel.pieShow.value == false) {
            when (oneId) {
                1027, 1033 -> {
                    //计划
                    clickStep(
                        oneId,
                        if (viewModel.planSelectData.size == 0) null else viewModel.planSelectData[0]
                    )
                    viewModel.pieShow.value = true
                    binding.trainLayout.visibility = View.GONE
                    binding.trainTurn.visibility = View.VISIBLE
                }
                1028 -> {
                    //动作设定
                    trainStepSettingFragment?.let {
                        it.getSelectBean()
                    }
                }
                1030 -> {
                    //跑步时间
                    trainRunTimeFragment?.let {
                        viewModel.runLiveData = it.returnData()
                        clickStep(
                            oneId,
                            if (viewModel.planSelectData.size == 0) null else viewModel.planSelectData[0]
                        )
                        viewModel.pieShow.value = true
                        binding.trainLayout.visibility = View.GONE
                        binding.trainTurn.visibility = View.VISIBLE

                    }
                }
                1032 -> {
                    //运动场景
                    trainRunSceneFragment?.let {
                        it.getSelectBean()
                    }
                }

            }
        } else {
            //这里是图表点击
            when (oneId) {
                1027 -> {

                    //运动计划
                    childFragmentManager.replaceFragment(
                        RouteManager.getInstance()
                            .getTrainStepTrainFragment(viewModel.getcategoryNames()).also {
                                it.setOnLabelCheckedListener { e ->
                                    viewModel.planSelectData = e
                                }
                            }, R.id.train_layout
                    )
                    viewModel.pieShow.value = false
                    binding.trainLayout.visibility = View.VISIBLE
                    binding.trainTurn.visibility = View.GONE
                }
                1028 -> {
                    //动作设定
                    //这里要判断是否已经选择锻炼部位 1018
                    viewModel.trainStepSelectList.value?.let {
                        if (it.contains(TrainSelectData(1018, null))) {
                            var child = viewModel.trainStepSelectList.getData(
                                TrainSelectData(
                                    1018,
                                    null
                                )
                            ).child as String
                            trainStepSettingFragment =
                                RouteManager.getInstance().getTrainStepSettingFragment(child)
                            trainStepSettingFragment?.let {
                                it.setOnLabelCheckedListener { e ->
                                    //动作设定回调
                                    viewModel.currentSelectOneType.clear()
                                    //获取当前entityX
                                    viewModel.currentSelectOneType.add(
                                        viewModel.getSelectOneXById(
                                            oneId
                                        )
                                    )
                                    viewModel.pieShow.value = true
                                    binding.trainLayout.visibility = View.GONE
                                    binding.trainTurn.visibility = View.VISIBLE
                                    viewModel.planSettingData = e
                                    clickStep(oneId, viewModel.planSettingData)
                                    var toList = viewModel.trainStepSelectList.value!!.stream()
                                        .map { it.oneX }.toList() as List<Int>
                                    inside_chart.setMoreDataColors(
                                        viewModel.currentSelectOneType,
                                        toList
                                    )
                                }
                                childFragmentManager.replaceFragment(it, R.id.train_layout)
                            }
                            viewModel.pieShow.value = false
                            binding.trainTurn.visibility = View.GONE
                            binding.trainLayout.visibility = View.VISIBLE
                        } else {
                            ToastUtils.showShort("请选中第一步！")
                        }
                    }

                }
                1030 -> {
                    //运动时间
                    childFragmentManager.replaceFragment(
                        RouteManager.getInstance().getTrainRunTimeFragment().also {
                            trainRunTimeFragment = it
                        }, R.id.train_layout
                    )
                    viewModel.pieShow.value = false
                    binding.trainLayout.visibility = View.VISIBLE
                    binding.trainTurn.visibility = View.GONE
                }
                1032 -> {
                    //运动场景
                    trainRunSceneFragment =
                        RouteManager.getInstance().getTrainRunSceneFragment(oneId.toString())
                    trainRunSceneFragment?.let {
                        it.setOnLabelCheckedListener { e ->
                            //动作设定回调
                            viewModel.currentSelectOneType.clear()
                            //获取当前entityX
                            viewModel.currentSelectOneType.add(
                                viewModel.getSelectOneXById(
                                    oneId
                                )
                            )
                            viewModel.pieShow.value = true
                            binding.trainLayout.visibility = View.GONE
                            binding.trainTurn.visibility = View.VISIBLE
                            viewModel.runScenesLiveData = e
                            clickStep(oneId, viewModel.runScenesLiveData)
                            var toList = viewModel.trainStepSelectList.value!!.stream()
                                .map { it.oneX }.toList() as List<Int>
                            inside_chart.setMoreDataColors(
                                viewModel.currentSelectOneType,
                                toList
                            )
                        }
                        childFragmentManager.replaceFragment(it, R.id.train_layout)
                    }
                    viewModel.pieShow.value = false
                    binding.trainTurn.visibility = View.GONE
                    binding.trainLayout.visibility = View.VISIBLE

                }
                1033 -> {
                    //运动计划
                    childFragmentManager.replaceFragment(
                        RouteManager.getInstance().getTrainStepTrainFragment().also {
                            it.setOnLabelCheckedListener { e ->
                                viewModel.planSelectData = e
                            }
                        }, R.id.train_layout
                    )
                    viewModel.pieShow.value = false
                    binding.trainLayout.visibility = View.VISIBLE
                    binding.trainTurn.visibility = View.GONE
                }
            }
        }
    }

    fun clickStep(oneId: Int, obj: Any?) {
        var trainSelectData = TrainSelectData(oneId, obj, viewModel.currentSelectOneType[0])
        var value = viewModel.trainStepSelectList.value
        if (value!!.contains(trainSelectData)) {
            value.remove(trainSelectData)
        }
        value.add(trainSelectData)

        viewModel.trainStepSelectList.value = value
//        var onList = viewModel.trainStepList.value
//        Collections.sort(onList, object : Comparator<TrainListBeanInfo?> {
//            override fun compare(o1: TrainListBeanInfo?, o2: TrainListBeanInfo?): Int {
//                var index = value.indexOf(TrainSelectData(o2!!.id, null))
//                if (index == -1) {
//                    if (o2!!.id == 1018) {
//                        return -2;
//                    }
//                    if (o2!!.id == 1028) {
//                        return -3;
//                    }
//                }
//                return index
//            }
//        })
//        viewModel.trainStepList.synchronouscallValue()
        if (viewModel.trainStepList.size > getCurrentStep()) {
            //TODO trainStepSelectList 这个类是一级选中的ID
            //TODO trainStepList一级分类列表
            for (trainListBeanInfo in viewModel.trainStepList.value!!) {
                var tempData=TrainSelectData(trainListBeanInfo.id)
                if(!viewModel.trainStepSelectList.value!!.contains(tempData)){
                    inside_chart.AngleByIndex(
                        viewModel.trainStepList.value!!.indexOf(
                            trainListBeanInfo
                        )
                    )
                    break
                }
            }
            inside_chart.invalidate()
            if (oneId == 1018) {
                //锻炼部位 要重置动作设定
                viewModel.trainStepSelectList.deleteList(TrainSelectData(1028, null))
                //然后直接跳到动作设定的模式 1028
                clickJump(1028)
            }
        }
    }

    fun getCurrentStep(): Int = viewModel.trainStepSelectList.size

}
